﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartMathLibrary;

namespace SmartMathLibrary.NumericalIntegration
{
    /// <summary>
    /// This class provides an integration for linear splines.
    /// </summary>
    [Serializable]
    public class FullLinearSplineIntegrator : AbstractSplineIntegrator
    {
        /// <summary>
        /// This field holds the spline to integrate.
        /// </summary>
        private ILinearSpline integral;

        /// <summary>
        /// Initializes a new instance of the <see cref="FullLinearSplineIntegrator"/> class.
        /// </summary>
        /// <param name="integral">The spline to integrate.</param>
        public FullLinearSplineIntegrator(ILinearSpline integral)
        {
            this.integral = integral;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="FullLinearSplineIntegrator"/> class.
        /// </summary>
        /// <param name="integral">The spline to integrate.</param>
        public FullLinearSplineIntegrator(LinearSpline integral)
        {
            this.integral = integral;
        }

        /// <summary>
        /// Gets or sets the spline to integrate.
        /// </summary>
        /// <value>The spline to integrate.</value>
        public ILinearSpline Integral
        {
            get { return integral; }
            set { integral = value; }
        }

        /// <summary>
        /// Integrates the spline in a numerical way.
        /// </summary>
        /// <returns>The value of the intergral.</returns>
        public override double Integrate()
        {
            double result = 0;

            foreach (LinearSplineComponent component in this.integral.Components)
            {
                result += InternalIntegrate(component);
            }

            return result;
        }

        private static double InternalIntegrate(LinearSplineComponent component)
        {
            SimplePolynomial upgrade = new SimplePolynomial(0, component.LinearFunction.TranslationConstant,
                                                            component.LinearFunction.Slope / 2);

            return upgrade.SolveAt(Math.Max(component.Start.X, component.End.X)) -
                   upgrade.SolveAt(Math.Min(component.Start.X, component.End.X));
        }
    }
}